import request from "./request";

export default (urlMap, rootUrl) => {
    const obj = {};
    for (const key in urlMap) {
      obj[key] = (source, save) => {
        const postData = urlMap[key];
        let postDataItem =
          "submitData" in postData
            ? JSON.parse(JSON.stringify(postData.submitData))
            : null;
        // if(postData.ContentType=='rest'){
        //   postData.url=postData.url+'/'+source;
        // }
        if(postData.ContentType=='rest'){
          postDataItem=source;
        }else if (postDataItem !== null) {
          for (const item in postDataItem) {
            const sourceItem = postDataItem[item];
            postDataItem[item] = source[sourceItem];
          }
        }
        // console.log(postDataItem)
        // console.log(postData)
        const response = request(
          postData.method,
          rootUrl+postData.url,
          postDataItem,
          postData.ContentType
        );
        if (!("reponseGetter" in postData))
          return response.then((res) => {
            // if (res > 0) alert("操作成功");
            // else alert("操作失败");
            return res;
          });
        else
          return response.then((res) => {
            const resGet =
              postData.reponseGetter;
            if (resGet.type == "array") {
              save.splice(
                0,
                save.length,
                ...resGet.resSource.reduce(
                  (total, current) => total[current],
                  res
                )
              );
            } else if(resGet.type == 'ref'){
              save.value = res[resGet.value]
            } else if(resGet.type == 'obj') {
              for(const key in res){
                save[key] = res[key]
              }
            }
          });
      };
    }
    // console.log(obj);
    return obj;
  };